package cn.renhui.hermesbus.core;

import android.text.TextUtils;

import com.google.gson.Gson;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

import cn.renhui.hermesbus.utils.LogUtils;
import cn.renhui.hermesbus.Response;
import cn.renhui.hermesbus.bean.ResponseBean;

public class HermesInvocationHander implements InvocationHandler {

    private Class aClass;
    private Class hermeService;

    private Gson gson = new Gson();

    public HermesInvocationHander(Class hermeService, Class aClass) {
        this.hermeService = hermeService;
        this.aClass = aClass;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        LogUtils.e("invoke hermeServiceName = " + hermeService);
        LogUtils.e("invoke aClass = " + aClass);
        Response response = Hermes.getDefault().sendObjectRequest(hermeService, aClass, method, args);
        if (!TextUtils.isEmpty(response.getData())) {
            ResponseBean responseBean = gson.fromJson(response.getData(), ResponseBean.class);
            if (responseBean.getData() != null) {
                Object responseBeanData = responseBean.getData();
                String data = gson.toJson(responseBeanData);
                Class returnType = method.getReturnType();
                Object obj = gson.fromJson(data, returnType);
                return obj;
            }
        }
        return null;
    }
}